// Copyright (c) 2011, Grant China
// All rights reserved.

package org.gwtlcars.ui;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.HasClickHandlers;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Widget;

public class LcarsRadioButton extends Composite implements HasClickHandlers {

    private static LcarsRadioButtonUiBinder uiBinder = GWT
            .create(LcarsRadioButtonUiBinder.class);

    interface LcarsRadioButtonUiBinder extends
            UiBinder<Widget, LcarsRadioButton> {
    }

    @UiField
    Button button;

    private LcarsRadioButtonGroup parent;
    private String upColor = LcarsColor.LIGHT_ORANGE;
    private String downColor = LcarsColor.LIGHT_YELLOW;
    private ClickHandler click_handler = null;

    public LcarsRadioButton(String upText) {
        initWidget(uiBinder.createAndBindUi(this));
        button.setText(upText);
        setEnabled(false);
    }

    public void setParent(LcarsRadioButtonGroup p) {
        parent = p;
    }

    @UiHandler("button")
    void onClick(ClickEvent e) {
        for (Widget w : parent.getChildren()) {
            if (w == this)
                setEnabled(true);
            else
                ((LcarsRadioButton) w).setEnabled(false);
        }

        if (click_handler != null)
            click_handler.onClick(e);
    }

    void setEnabled(boolean enabled) {
        button.removeStyleName(enabled ? upColor : downColor);
        button.addStyleName(enabled ? downColor : upColor);
    }

    @Override
    public HandlerRegistration addClickHandler(ClickHandler handler) {
        click_handler = handler;
        return null;
    }
}
